﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.MODEL;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.DBM;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_PrintPreview : System.Web.UI.Page
    {
        Main main = new Main();
        string type = "rq";
        private IProject projectBLL;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                type = Request.QueryString["type"];
                projectBLL = Project_Factory.GetProjectFactory(type);
                LoadData(Session["ProjectID"].ToString());
                
                //LoadData("149");
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        public void LoadData(string strBgmReqSeq)
        {
            lblBgmReqSeq.Text = strBgmReqSeq;

            LoadProjectInfo();
            LoadRepeaterBgmSource();
        }

        protected void LoadProjectInfo()
        {
            string strBgmReqSeq = lblBgmReqSeq.Text;
            DataTable dtb = projectBLL.GetDataProjectBySequence(strBgmReqSeq);
            lbBgmYear.Text = dtb.Rows[0]["bgm_year"].ToString();
            lblBgmReqSeq.Text = dtb.Rows[0]["Sequence"].ToString();
            lbProjDate.Text = main.ConvertDBDateTimeToString(dtb.Rows[0]["bgm_prj_date"], true);
            lbProjJobSite.Text = dtb.Rows[0]["job_site_name"].ToString();
            lbProjName.Text = dtb.Rows[0]["bgm_prj_name"].ToString();
            lbProjObject.Text = dtb.Rows[0]["bgm_prj_object"].ToString().Replace("\r\n", "<br />");
            lbProjPlan.Text = dtb.Rows[0]["bgm_prj_plan"].ToString().Replace("\r\n", "<br />");
            lbProjAim.Text = dtb.Rows[0]["bgm_prj_aim"].ToString().Replace("\r\n", "<br />");
            lbProjProfit.Text = dtb.Rows[0]["bgm_prj_profit"].ToString().Replace("\r\n", "<br />");
            lbProjReason.Text = dtb.Rows[0]["bgm_prj_reason"].ToString().Replace("\r\n", "<br />");
            lbProjRemark.Text = dtb.Rows[0]["bgm_prj_remark"].ToString().Replace("\r\n", "<br />");
            lbProjScope.Text = dtb.Rows[0]["bgm_scope_name"].ToString();
            lbProjStrat.Text = dtb.Rows[0]["bgm_strat_list_name"].ToString();
            lbProjTarget.Text = dtb.Rows[0]["bgm_prj_target"].ToString().Replace("\r\n", "<br />");
            lbProjType.Text = dtb.Rows[0]["prj_type_name"].ToString();
            lblStartDate.Text = main.ConvertDBDateTimeToString(dtb.Rows[0]["date_start"], true);
            lblEndDate.Text = main.ConvertDBDateTimeToString(dtb.Rows[0]["date_end"], true);

            IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
            dbManager.CreateParameters(2);
            dbManager.AddParameters(0, "@RecordStatus", SystemInfo._ActiveRecordStatus);
            dbManager.AddParameters(1, "@seq", strBgmReqSeq);

            string strSQL = "";

            if (type == "rq")
            {
                strSQL = "select e.bgm_exp_seq as value"
                    + ", concat(e.bgm_exp_name"
                        + ", case when re.icm_res_item_seq is not null"
                            + " then concat('/', coalesce(item.name, ''))"
                            + " else ''"
                            + " end) as text"
                    + ", re.total_amount"
                    + ", re.bgm_req_exp_seq as bgm_proj_exp_seq"
                    + ", re.bgm_source_seq, s.bgm_source_name"
                    + ", eg.bgm_exp_grp_seq, eg.bgm_exp_grp_name, eg.bgm_exp_grp_x"
                    + ", e1.bgm_exp_seq as bgm_exp_seq_1, e1.bgm_exp_name as bgm_exp_name_1"
                    + ", e2.bgm_exp_seq as bgm_exp_seq_2, e2.bgm_exp_name as bgm_exp_name_2"
                    + ", re.unit_price ,re.unit_qty ,re.descr"
                    + ", re.icm_res_item_seq, re.unit_price, re.unit_qty"
                    + " from bgm_mas_expense e"
                    + " left join bgm_mas_expense_group eg on e.bgm_exp_grp_seq = eg.bgm_exp_grp_seq"
                    + " left join bgm_mas_expense e1 on e1.bgm_exp_seq = e.upper_bgm_exp_seq"
                    + " left join bgm_mas_expense e2 on e2.bgm_exp_seq = e1.upper_bgm_exp_seq"
                    + " left join bgm_request_expense re on re.bgm_exp_seq = e.bgm_exp_seq"
                        + " and re.bgm_req_seq = @seq"
                    + " left join bgm_mas_source s on re.bgm_source_seq = s.bgm_source_seq"
                    + " left join IcmMasResourceItem item on re.icm_res_item_seq = item.ResItemId"

                    + " where e.bgm_exp_seq not in (select upper_bgm_exp_seq"
                            + " from bgm_mas_expense"
                            + " where record_status = 'A'"
                            + " and upper_bgm_exp_seq is not null)"
                        + " and re.bgm_req_seq = @seq"
                    + " order by eg.bgm_exp_grp_code, e.bgm_exp_name";
            }
            else
            {
                strSQL = "select e.bgm_exp_seq as value"
                    + ", concat(e.bgm_exp_name"
                        + ", case when re.icm_res_item_seq is not null"
                            + " then concat('/', coalesce(item.name, ''))"
                            + " else ''"
                            + " end) as text"
                    + ", re.total_amount"
                    + ", re.bgm_proj_exp_seq as bgm_proj_exp_seq"
                    + ", re.bgm_source_seq, s.bgm_source_name"
                    + ", eg.bgm_exp_grp_seq, eg.bgm_exp_grp_name, eg.bgm_exp_grp_x"
                    + ", e1.bgm_exp_seq as bgm_exp_seq_1, e1.bgm_exp_name as bgm_exp_name_1"
                    + ", e2.bgm_exp_seq as bgm_exp_seq_2, e2.bgm_exp_name as bgm_exp_name_2"
                    + ", re.unit_price ,re.unit_qty ,re.descr"
                    + ", re.icm_res_item_seq, re.unit_price, re.unit_qty"
                    + " from bgm_mas_expense e"
                    + " left join bgm_mas_expense_group eg on e.bgm_exp_grp_seq = eg.bgm_exp_grp_seq"
                    + " left join bgm_mas_expense e1 on e1.bgm_exp_seq = e.upper_bgm_exp_seq"
                    + " left join bgm_mas_expense e2 on e2.bgm_exp_seq = e1.upper_bgm_exp_seq"
                    + " left join bgm_project_expense re on re.bgm_exp_seq = e.bgm_exp_seq"
                        + " and re.bgm_proj_seq = @seq"
                    + " left join bgm_mas_source s on re.bgm_source_seq = s.bgm_source_seq"
                    + " left join IcmMasResourceItem item on re.icm_res_item_seq = item.ResItemId"

                    + " where e.bgm_exp_seq not in (select upper_bgm_exp_seq"
                            + " from bgm_mas_expense"
                            + " where record_status = 'A'"
                            + " and upper_bgm_exp_seq is not null)"
                        + " and re.bgm_proj_seq = @seq"
                    + " order by eg.bgm_exp_grp_code, e.bgm_exp_name";
            }

            dbManager.Open();
            DataTable dtb2 = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
            dbManager.Dispose();

            gridExpense.DataSource = dtb2;
            gridExpense.DataBind();

            gridManager.DataSource = projectBLL.GetDataProjectManager(strBgmReqSeq);
            gridManager.DataBind();

            gridMarket.DataSource = projectBLL.GetDataProjectOption(strBgmReqSeq, "3");
            gridMarket.DataBind();

            string strWarnning = "";

            if (dtb2.Rows.Count == 0)
            {
                strWarnning = "คำเตื่อน!! โครงการนี้ยังไม่มีค่าใช้จ่ายภายในโครงการ";
            }

            lblError.Text = strWarnning;
        }

        protected void LoadRepeaterBgmSource()
        {
            string strBgmReqSeq = lblBgmReqSeq.Text;

            IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
            dbManager.CreateParameters(2);
            dbManager.AddParameters(0, "@RecordStatus", SystemInfo._ActiveRecordStatus);
            dbManager.AddParameters(1, "@seq", strBgmReqSeq);

            string strSQL = "";

            if (type == "rq")
            {
                strSQL = "select s.bgm_source_name"
                     + ", sum(coalesce(re.total_amount,0)) as total_amount"
                     + " from bgm_request_expense re"
                     + " left join bgm_mas_source s on re.bgm_source_seq = s.bgm_source_seq"

                     + " where re.bgm_req_seq = @seq"
                     + " group by re.bgm_source_seq, s.bgm_source_name "
                     + " order by re.bgm_source_seq";
            }
            else
            {
                strSQL = "select s.bgm_source_name"
                     + ", sum(coalesce(re.total_amount,0)) as total_amount"
                     + " from bgm_project_expense re"
                     + " left join bgm_mas_source s on re.bgm_source_seq = s.bgm_source_seq"

                     + " where re.bgm_proj_seq = @seq"
                     + " group by re.bgm_source_seq, s.bgm_source_name "
                     + " order by re.bgm_source_seq";
            }
            dbManager.Open();
            DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

            RepeaterBgmSource.DataSource = dtb;
            RepeaterBgmSource.DataBind();

            dbManager.Dispose();
        }

        protected void RepeaterBgmSource_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType == ListItemType.Footer)
                {
                    string strBgmReqSeq = lblBgmReqSeq.Text;

                    IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
                    dbManager.CreateParameters(2);
                    dbManager.AddParameters(0, "@RecordStatus", SystemInfo._ActiveRecordStatus);
                    dbManager.AddParameters(1, "@seq", strBgmReqSeq);

                    dbManager.Open();
                    string strSQL = "";

                    if (type == "rq")
                    {
                        strSQL = "select sum(coalesce(re.total_amount,0)) as total_amount"
                            + " from bgm_request_expense re"

                            + " where re.bgm_req_seq = @seq"
                            + " group by re.bgm_req_seq";
                    }
                    else
                    {
                        strSQL = "select sum(coalesce(re.total_amount,0)) as total_amount"
                            + " from bgm_project_expense re"

                            + " where re.bgm_proj_seq = @seq"
                            + " group by re.bgm_proj_seq";
                    }

                    DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                    if (dtb.Rows.Count > 0)
                    {
                        ((Label)e.Item.FindControl("lblSumTotalAmount")).Text = Convert.ToDouble(dtb.Rows[0][0]).ToString("#,###.00");
                    }
                    dbManager.Dispose();
                }
            }
        }

        protected void cmdExportToMsWord_Click(object sender, EventArgs e)
        {
            ExportToMsWord();
        }

        protected void ExportToMsWord()
        {
            string strFileName = "Export-.doc";
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-word";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
            //EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            gridExpense.RegisterWithScriptManager = false;
            gridManager.RegisterWithScriptManager = false;
            gridMarket.RegisterWithScriptManager = false;

            PanelSummary.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
    }
}